package sk.dvsk.maven.doxia.macro;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.maven.doxia.macro.AbstractMacro;
import org.apache.maven.doxia.macro.MacroExecutionException;
import org.apache.maven.doxia.macro.MacroRequest;
import org.apache.maven.doxia.sink.Sink;

/**
 * @plexus.component role="org.apache.maven.doxia.macro.Macro" role-hint="code-snippet"
 */
public class CodeSnippetMacro extends AbstractMacro 
{
	private static final String DEFAULT_ENCODING = "UTF-8";

	public void execute(Sink sink, MacroRequest request)
			throws MacroExecutionException {

		String id = (String) request.getParameter("id");
		String code = (String) request.getParameter("code");
		String encoding = (String) request.getParameter("encoding");

		if(encoding == null) encoding = DEFAULT_ENCODING;
		
		URL url = getResourceURL(request);
		
		Snippet snippet;
		try {
			snippet = new Snippet(id, url, encoding);

			if(code != null) snippet.setCodeType(code);

			sink.rawText(snippet.toString());
		} catch (IOException e) {
			throw new MacroExecutionException("url=" + url, e);
		}
	}

	private static URL getResourceURL(MacroRequest request) {
		String urlParam = (String) request.getParameter("url");
		String fileParam = (String) request.getParameter("file");
		
		if (urlParam != null) {
			try {
				return new URL(urlParam);
			} catch (MalformedURLException e) {
				throw new IllegalArgumentException(urlParam + " is a malformed URL");
			}
		} else if (fileParam != null) {
			File f = new File(fileParam);

			if (!f.isAbsolute())
				f = new File(request.getBasedir(), fileParam);

			try {
				return f.toURI().toURL();
			} catch (MalformedURLException e) {
				throw new IllegalArgumentException(fileParam + " is a malformed URL");
			}
		} else {
			throw new IllegalArgumentException(
					"Either the 'url' or the 'file' param has to be given.");
		}
	}
}
